package parser;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import utils.BeanUtils;
import utils.StringUtils;

import common.StrutsStaticParams;

import model.BaseBean;
import model.DefaultParams;
import model.XMLBean;

public class XMLParser 
{
	public static Map<String, BaseBean> parserXML(File file) throws DocumentException
	{
		Map<String, BaseBean> map = new HashMap<String, BaseBean>();
		XMLBean bean = null;
		DefaultParams dp = null;
		SAXReader reader = new SAXReader();
		Document document = reader.read(file);
		Element root = document.getRootElement();
		Iterator i = root.elementIterator();

		while(i.hasNext())
		{
			Element element = (Element) i.next();
			
			if(element.getName().equals("action"))
			{
				bean = new XMLBean();
				
				bean.setActionName(element.attributeValue("name"));
				bean.setClassPath(element.attributeValue("class"));
				Iterator child = element.elementIterator();
				Map<String, String> resultMap = new HashMap<String, String>();
				while(child.hasNext())
				{
					Element result = (Element)child.next();
					resultMap.put(result.attributeValue("name"), result.getData().toString());
					bean.setResult(resultMap);
				}
				map.put(bean.getActionName(), bean);
			}
			else if(element.getName().equals("constant"))
			{
				String name = element.attributeValue("name");
				String value = element.attributeValue("value");
				
				if(!StringUtils.isBlank(name) && !StringUtils.isBlank(value))
				{
					dp = (DefaultParams) map.get(StrutsStaticParams.DEFAULTPARAMS);
					if(dp == null)
						dp = new DefaultParams();
					BeanUtils.transform(dp, name, value);
					map.put(StrutsStaticParams.DEFAULTPARAMS, dp);
				}
			}
		}
	
		return map;
	}
}
